﻿using LanguagePolish.EntityModel;
using LanguagePolish.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Xceed.Wpf.Toolkit;

namespace LanguagePolish.Views
{
    /// <summary>
    /// Логика взаимодействия для AddTeacherView.xaml
    /// </summary>
    public partial class AddTeacherView : Window
    {
        private readonly AddTeacherViewModel vm;

        int teacherID;
        public AddTeacherView(Teacher teacher, bool isEdit = false)
        {
            InitializeComponent();
            teacherID = teacher.TeacherID;
            vm = new AddTeacherViewModel(teacher, isEdit);
            DataContext = vm;
            UpdateOkButtonState();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void btnUser_Click(object sender, RoutedEventArgs e) 
        {
            var context = LinksProvider.Model.EntityContext;
            AddUserView auw;
            if (context.Users.Any(x => x.TeacherID == this.teacherID))
            {
                auw = new AddUserView(context.Users.First(x => x.TeacherID == this.teacherID), teacherID, true);
                auw.ShowDialog();
            }
            else 
            {
                User newUser = new User();
                auw = new AddUserView(newUser, teacherID);
                auw.ShowDialog();
            }
            context.SaveChanges();
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            UpdateOkButtonState();
        }

        private void UpdateOkButtonState()
        {
            // активация кнопки ОК в зависимости от валидности данных
            btnOk.IsEnabled = !vm.HasErrors;
        }

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            vm.LoadImage();
        }
    }
}
